package com.button.file.application.service.impl;

import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import com.button.file.application.conf.FileLoadProperties;
import com.button.file.application.exception.FileException;
import com.button.file.application.service.FileDownloadService;

@Service
public class FileDownloadServiceImpl implements FileDownloadService {
	private final Path fileStorageLocation; // 文件在本地存储的地址

	@Autowired
	public FileDownloadServiceImpl(FileLoadProperties fileProperties) {
		this.fileStorageLocation = Paths.get(fileProperties.getUploadDir()).toAbsolutePath().normalize();
		try {
			Files.createDirectories(this.fileStorageLocation);
		} catch (Exception ex) {
			throw new FileException("保存文件创建目录时发生异常. .", ex);
		}
	}

	/**
	 * 加载文件
	 * 
	 * @param fileName 文件名
	 * @return 文件
	 */
	@Override
	public Resource loadFileAsResource(String fileName) {
		try {
			Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
			Resource resource = new UrlResource(filePath.toUri());
			if (resource.exists()) {
				return resource;
			} else {
				throw new FileException("File not found " + fileName);
			}
		} catch (MalformedURLException ex) {
			throw new FileException("File not found " + fileName, ex);
		}
	}
}
